package ca.usask.cs.drawTree;

import java.util.Iterator;

import com.nootropic.processing.layers.Layer;

import processing.core.PApplet;

public class VerticalScrollbar extends Layer {
	/**
	 * 
	 */
	private static final long serialVersionUID = 352938112027461836L;
	int swidth, sheight; // width and height of bar
	int xpos, ypos; // x and y position of bar
	float spos, newspos; // x position of slider
	int sposMin, sposMax; // max and min values of slider
	int loose; // how loose/heavy
	boolean over; // is the mouse over the slider?
	boolean locked;
	float ratio;
	float sypos;

	static final int VnormalColor = 0xff993300;
	static final int VseleteColor = 0xffFFFF00;
	DrawControler controler;

	public VerticalScrollbar(int xp, int yp, int sw, int sh, int l,
			PApplet parent) {
		super(parent); // This is necessary!
		swidth = sw;
		sheight = sh;
		int widthtoheight = sw - sh;
		ratio = (float) sw / (float) widthtoheight;
		xpos = xp;
		ypos = yp - sheight / 2;
		// spos = xpos + swidth/2 - sheight/2;

		sypos = ypos + sheight / 2;

		newspos = sypos;
		sposMin = ypos;
		sposMax = ypos + sheight - swidth;
		loose = l;
		controler = (DrawControler) parent;
	}

	void update() {
		if (over()) {
			over = true;
		} else {
			over = false;
		}
		if (controler.mousePressed && over && controler.HbarSeleted == false) {
			locked = true;
			controler.VbarSeleted = true;
		}
		if (!controler.mousePressed) {
			locked = false;
		}
		if (locked) {
			newspos = constrain(controler.mouseY - swidth / 2, sposMin, sposMax);
		}
		if (controler.abs(newspos - sypos) > 1) {
			sypos = sypos + (newspos - sypos) / loose;
			
//			
//			Iterator iterator = controler.nodes.keySet().iterator();    
//			while (iterator.hasNext()){
//				(controler.nodes.get(iterator.next())).y=(controler.nodes.get(iterator.next())).y+sypos; 
//			}
//			controler.rooty = sypos;
//			controler.init = false;
			controler.VerticalScrollBarUpdate((newspos - sypos) / loose);
		}
	}

	int constrain(int val, int minv, int maxv) {
		return controler.min(controler.max(val, minv), maxv);
	}

	boolean over() {
		if (controler.mouseX > xpos && controler.mouseX < xpos + swidth
				&& controler.mouseY > ypos && controler.mouseY < ypos + sheight) {
			return true;
		} else {
			return false;
		}
	}

	public void draw() {
		fill(255);
		smooth();
		strokeWeight(2);
		rect(xpos, ypos, swidth, sheight);
		if ((over || locked) && (controler.HbarSeleted == false)) {
			fill(VseleteColor);
		} else {
			controler.VbarSeleted = false;
			fill(VnormalColor);
		}
		rect(xpos, sypos, swidth, swidth + 10);
//		controler.updatedrawtheNodes();
//		controler.updatedrawEdges();
		update();

	}

	float getPos() {
		// Convert spos to be values between
		// 0 and the total width of the scrollbar
		return sypos * ratio;
	}

}
